package com.lv.suyiyong.hfr.ui

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.view.get
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.setViewFlipper
import com.lv.common.ktx.viewLifeCycleOwner
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.ADBean
import com.lv.service.bean.ADMoreBean
import com.lv.service.bean.FindProsBean
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.PageNameIdBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxAroutPageKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.WholeGoodsAdapter
import com.lv.suyiyong.hfr.databinding.ActivityWholeSaleBinding
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.listener.OnBannerListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：批发好价
 */
@Route(path = ARoutUtils.WholeSalerActivity)
class WholeSalerActivity : BaseActivity<ActivityWholeSaleBinding>(), View.OnClickListener {
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val mBannerFristData = mutableListOf<ADBean>()
    private val mBannerSecoundData = mutableListOf<ADBean>()
    private var mBannerFristAdapter: BannerImageAdapter<ADBean>? = null
    private var mBannerSecoundAdapter: BannerImageAdapter<ADBean>? = null
    private val mTopIv =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/icon_whole_sale.png"
    private var mUserInfo: UserInfo? = null
    private val mFristBeans = mutableListOf<GoodsItemBean>()
    private val mSecoundBeans = mutableListOf<GoodsItemBean>()
    private val mBeans = mutableListOf<GoodsItemBean>()
    private var mFristAdapter: WholeGoodsAdapter? = null
    private var mSecoundAdapter: WholeGoodsAdapter? = null
    private var mAdapter: WholeGoodsAdapter? = null
    private var mRvFrist: RecyclerView? = null
    private var mRvSecound: RecyclerView? = null
    private var mBannerFrist: Banner<*, *>? = null
    private var mBannerSecound: Banner<*, *>? = null
    private var mVHeadSub: View? = null
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_whole_sale
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@WholeSalerActivity, viewStatus)
            ivBackPage.setOnClickListener { finish() }
            initSingleClickListener(viewSearch)
        }
    }


    override fun initConfig() {
        super.initConfig()
        initAdapter()
        mBinding.ivTitlePage.LoadSrc(mTopIv)
        initBannerAdapter()
        bannerObserver()
        lifecycleScope.launchWhenCreated {
            val taskFindBanner = async {
                val findAllBannerResult = findAllBannerSuspend()
                parseFindAllBannerResult(findAllBannerResult)
            }
            taskFindBanner.await()
            saleByBulk()
        }
        findPros()
        UserDbHelper.getLiveUserInfo(this).observeKt {
            mUserInfo = it
        }
    }


    private fun initAdapter() {
        val gridLayoutManager = GridLayoutManager(this, 3)
        mBinding.rvContent.layoutManager = gridLayoutManager
        mAdapter = WholeGoodsAdapter(mBeans)
        mBinding.rvContent.adapter = mAdapter
        mBinding.rvContent.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(5.0f), SizeUtils.dp2px(5.0f), true
            )
        )
        val headerView = layoutInflater.inflate(
            R.layout.whole_sale_header, null, false
        )
        mRvFrist = headerView.findViewById<RecyclerView>(R.id.rv_frist)
        mBannerFrist = headerView.findViewById<Banner<*, *>>(R.id.banner_frist)
        mRvSecound = headerView.findViewById<RecyclerView>(R.id.rv_secound)
        mBannerSecound = headerView.findViewById<Banner<*, *>>(R.id.banner_secound)
        mVHeadSub = headerView.findViewById<View>(R.id.v_head_sub)
        mAdapter?.addHeaderView(headerView)

        val gridFristManager = object : GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRvFrist?.layoutManager = gridFristManager
        mFristAdapter = WholeGoodsAdapter(mFristBeans)
        mRvFrist?.adapter = mFristAdapter
        val gridSecoundManager = object : GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRvSecound?.layoutManager = gridSecoundManager
        mSecoundAdapter = WholeGoodsAdapter(mSecoundBeans)
        mRvSecound?.adapter = mSecoundAdapter

        mRvFrist?.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(5.0f), SizeUtils.dp2px(5.0f), false
            )
        )
        mRvSecound?.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(5.0f), SizeUtils.dp2px(5.0f), false
            )
        )
    }

    private suspend fun findAllBannerSuspend(): DataResult<BaseYgxRsp> {
        return withContext(Dispatchers.IO) {
            myScope.async {
                serviceViewModel.findAllBanner("4")
            }.await()
        }
    }

    private fun parseFindAllBannerResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<ADMoreBean> { code, data, message, result ->
                mBannerFristData.clear()
                mBannerSecoundData.clear()
                val adlist1 = data?.adlist1
                adlist1?.let { mBannerFristData.addAll(it) }
                val adlist2 = data?.adlist2
                adlist2?.let { mBannerSecoundData.addAll(it) }
            }
            onBizError<Any> { code, message, data ->

            }
        }
        data.onFailure {

        }
    }

    private fun findPros() {
        val findProsMap = mutableMapOf("hotSearch" to "1")
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    serviceViewModel.findPros(findProsMap)
                }
            parseFindProsResult(result)
        }
    }

    private fun parseFindProsResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<FindProsBean> { code, data, message, result ->
                val hotSearch = data?.hotSearch
                hotSearch?.let {
                    setSearchData(hotSearch)
                }
            }
            onBizError<Any> { code, message, data ->

            }
        }
        data.onFailure {

        }
    }

    private fun setSearchData(titles: List<String>) {
        mBinding.marqueeBanner.setViewFlipper(this, titles, 3000) { i ->
            val mLayout: View =
                LayoutInflater.from(this)
                    .inflate(R.layout.item_text_flipper, null)
            val tvTitle = mLayout.findViewById<TextView>(R.id.tv_content)
            //赋值
            tvTitle.text = titles[i]
            tvTitle.setTextColor(Color.parseColor("#ffffff"))
            return@setViewFlipper mLayout
        }
    }


    private fun saleByBulk() {
        val body = PageNameIdBody(page, pageSize, "", emptyList())
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    serviceViewModel.saleByBulk(body)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                val items = data?.items
//                val list = items?.chunked(6)
                if (page == 1) {
                    mFristBeans.clear()
                    mSecoundBeans.clear()
                    mBeans.clear()
                    if (items.isNullOrEmpty()) {
                        mAdapter?.setEmptyView(getEmptyView(mBinding.rvContent))
                    } else {
                        val group1 = items.subList(0, minOf(6, items.size))
                        mFristBeans.addAll(group1)
                        mRvFrist?.visibility = View.VISIBLE
                        mFristAdapter?.notifyDataSetChanged()
                        if (items.size > 6) {
                            mRvSecound?.visibility = View.VISIBLE
                            val group2 = items.subList(6, minOf(12, items.size))
                            mSecoundBeans.addAll(group2)
                            mSecoundAdapter?.notifyDataSetChanged()
                            mBannerFrist?.visibility = View.VISIBLE
                            mBannerSecound?.visibility = View.VISIBLE
                            mBannerFristAdapter?.notifyDataSetChanged()
                            mBannerSecoundAdapter?.notifyDataSetChanged()
                            if (mBannerFristData.isEmpty()) {
                                YgxUtilsKt.parseBannerTime(
                                    mBannerFrist, mBannerFristData[0].startup
                                )
                            }
                            if (mBannerSecoundData.isEmpty()) {
                                YgxUtilsKt.parseBannerTime(
                                    mBannerSecound, mBannerSecoundData[0].startup
                                )
                            }
                        } else {
                            if (group1.isEmpty()) {
                                mBannerFrist?.visibility = View.GONE
                                mBannerSecound?.visibility = View.GONE
                            } else {
                                mBannerFrist?.visibility = View.VISIBLE
                                mBannerSecound?.visibility = View.GONE
                                if (mBannerFristData.isEmpty()) {
                                    YgxUtilsKt.parseBannerTime(
                                        mBannerFrist, mBannerFristData[0].startup
                                    )
                                }
                                mBannerFristData.addAll(mBannerSecoundData)
                                mBannerFristAdapter?.notifyDataSetChanged()
                            }
                        }
                        if (items.size > 12) {
                            val group3 = items.subList(12, items.size)
                            mBeans.addAll(group3)

                        }
                    }
                } else {
                    items?.let { mBeans.addAll(it) }
                }
                if (mBeans.isEmpty() && mBannerFristData.isNotEmpty()) {
                    mVHeadSub?.visibility = View.VISIBLE
                } else {
                    mVHeadSub?.visibility = View.GONE
                }
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.finishLoadMore()
                if (items.isNullOrEmpty() || items.size < pageSize) {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(true)
                }
                mAdapter?.notifyDataSetChanged()

            }
            onBizError<GoodsBean> { code, message, data ->

            }
        }
        data.onFailure {

        }
    }


    override fun initEvents() {
        super.initEvents()


    }

    override fun initData() {
        super.initData()

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_search -> {
                val text =
                    (mBinding.marqueeBanner.currentView?.findViewById<TextView>(R.id.tv_content)?.text
                        ?: "").toString()
                ARouter.getInstance().build(ARoutUtils.CommonSearchActivity)
                    .withString("search", text).navigation()
            }
        }
    }

    /**
     * 设置Banner适配器
     */
    private fun bannerObserver() {
        mBannerFrist?.addBannerLifecycleObserver(viewLifeCycleOwner)
            ?.setAdapter(mBannerFristAdapter)
            ?.setIntercept(false)
        mBannerSecound?.addBannerLifecycleObserver(viewLifeCycleOwner)
            ?.setAdapter(mBannerSecoundAdapter)
            ?.setIntercept(false)

    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mBannerFristAdapter = object : BannerImageAdapter<ADBean>(mBannerFristData) {
            override fun onBindView(
                holder: BannerImageHolder?,
                data: ADBean?,
                position: Int,
                size: Int
            ) {
                Glide.with(this@WholeSalerActivity)
                    .load(data?.image)
                    .into(holder?.imageView!!)
            }
        }

        mBannerFristAdapter?.setOnBannerListener(OnBannerListener<Any?> { data, position ->
//            mBannerFrist?.isAutoLoop(false)
            val indexCommon = mBannerFristData[position]
            YgxAroutPageKt.aroutPager(
                this,
                indexCommon.tag,
            )
//            mBannerTopData[position].statistics = -1
        })

        mBannerSecoundAdapter = object : BannerImageAdapter<ADBean>(mBannerSecoundData) {
            override fun onBindView(
                holder: BannerImageHolder?,
                data: ADBean?,
                position: Int,
                size: Int
            ) {
                Glide.with(this@WholeSalerActivity)
                    .load(data?.image)
                    .into(holder?.imageView!!)
            }
        }

        mBannerSecoundAdapter?.setOnBannerListener(OnBannerListener<Any?> { data, position ->
//            mBannerFrist?.isAutoLoop(false)
            val indexCommon = mBannerSecoundData[position]
            YgxAroutPageKt.aroutPager(
                this,
                indexCommon.tag,
            )
//            mBannerTopData[position].statistics = -1
        })
    }

}